const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const fs = require('fs-extra');
const logger = require('./utils/logger');

// 导入路由和服务
const webhookController = require('./controllers/webhookController');
const configController = require('./controllers/configController');
const deployController = require('./controllers/deployController');
const historyController = require('./controllers/historyController');

// 导入配置
const config = require('./config/default.json');

// 创建Express应用
const app = express();

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public', 'dist')));

// 开发模式下的Vue应用支持
if (process.env.NODE_ENV !== 'production') {
    app.use('/src', express.static(path.join(__dirname, 'src')));
}

// API路由
app.use('/api/webhook', webhookController);
app.use('/api/config', configController);
app.use('/api/deploy', deployController);
app.use('/api/history', historyController);

app.use('/api', (req, res) => {
    res.status(404).json({ success: false, message: 'API endpoint not found' });
});

// 对于SPA应用，所有非API路由都返回index.html
app.get('*', (req, res) => {
    if (process.env.NODE_ENV !== 'production') {
        // 开发模式下，前端由Vite开发服务器提供
        return res.status(200).send('<h1>Frontend is served by Vite Dev Server</h1><p>Please ensure your Vite development server is running on port 5173.</p>');
    }
    // 生产模式下，返回构建后的index.html
    res.sendFile(path.join(__dirname, 'public', 'dist', 'index.html'));
});

// 404处理
app.use((req, res) => {
  res.status(404).json({ 
    success: false, 
    message: '请求的资源不存在' 
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
    logger.error('应用错误:', err);
    res.status(500).json({ 
        success: false, 
        message: '服务器内部错误',
        error: process.env.NODE_ENV === 'development' ? err.message : '未知错误'
    });
});

// 启动服务器
const PORT = process.env.PORT || config.server.port;
const HOST = process.env.HOST || config.server.host;

app.listen(PORT, HOST, () => {
  logger.info(`Git Webhook部署系统启动成功`);
  logger.info(`服务器运行在 http://${HOST}:${PORT}`);
  
  // 确保必要的目录存在
  fs.ensureDirSync('./logs');
  fs.ensureDirSync('./temp');
  fs.ensureDirSync('./data');
  fs.ensureDirSync('./public/dist');
});

module.exports = app;